import request from '../utils/request';
import storage from '../utils/storage';
/**
 * @method Services 请求方法类封装
 * @description 封装了常用的异步请求方法，如get,post,put,delete,上传方法
 *  */
export default class Services {
  constructor(url, withAuth) {
    this.initRequestHeader = {
      'Content-Type': 'application/json',
    };
    this.requestHeader = {
      'X-Portal-Name': 'admin',
      'X-Portal-Organization-Code': '001',
    };
    this.url = url;
    this.withAuth = withAuth;
  }

  setRequestHeader(headers) {
    this.requestHeader = {
      ...this.requestHeader,
      ...headers,
    };
  }

  getRequestHeader({ withAuth, headers, isFormdata, isUpload }) {
    return Object.assign(
      {},
      isUpload
        ? this.requestHeader
        : {
          ...this.initRequestHeader,
          ...this.requestHeader,
        },
      headers,
      withAuth !== undefined
        ? withAuth
        : this.withAuth
          ? {
            // token: storage.token,
            // 'X-User-Dept-Id': storage.dept,
          }
          : {},
      isFormdata
        ? {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        }
        : {}
    );
  }

  // get
  get(api, { params, withAuth, headers, isLoading, errorCatch, errorCode, successCode, warningCode }) {
    const newUrl = params && Object.keys(params).length > 0 ? this.getParamsUrl(api, params) : api;
    return request(
      this.url + newUrl,
      {
        method: 'GET',
        headers: this.getRequestHeader({ withAuth, headers }),
      },
      { isLoading, errorCatch, errorCode, successCode, warningCode }
    );
  }

  // post
  post(api, { params, withAuth, headers, isFormdata, isLoading, errorCatch, errorCode, successCode, warningCode }) {
    return request(
      this.url + api,
      {
        method: 'POST',
        headers: this.getRequestHeader({ withAuth, headers, isFormdata }),
        body: isFormdata ? this.parseParams(params) : JSON.stringify(params),
      },
      { isLoading, errorCatch, errorCode, successCode, warningCode }
    );
  }

  // 编辑
  put(api, { params, withAuth, headers, isLoading, errorCatch, errorCode, successCode, warningCode }) {
    return request(
      this.url + api,
      {
        method: 'PUT',
        headers: this.getRequestHeader({ withAuth, headers }),
        body: JSON.stringify(params),
      },
      { isLoading, errorCatch, errorCode, successCode, warningCode }
    );
  }

  // 删除
  del(api, { withAuth, headers, isLoading, errorCatch, errorCode, successCode, warningCode }) {
    return request(
      this.url + api,
      {
        method: 'DELETE',
        headers: this.getRequestHeader({ withAuth, headers }),
      },
      { isLoading, errorCatch, errorCode, successCode, warningCode }
    );
  }

  // upload
  upload(api, { withAuth, params, isLoading, errorCode, successCode, warningCode }) {
    return request(
      this.url + api,
      {
        method: 'POST',
        headers: this.getRequestHeader({
          withAuth,
          isUpload: true,
        }),
        body: params,
      },
      { isLoading, errorCode, successCode, warningCode, content: '上传中...' }
    );
  }

  // options
  options(api, { params, withAuth, isLoading, errorCode, successCode, warningCode }) {
    return request(
      this.url + api,
      {
        method: 'OPTIONS',
        headers: this.getRequestHeader({
          withAuth,
        }),
        body: JSON.stringify(params),
      },
      { isLoading, errorCode, successCode, warningCode }
    );
  }

  // 处理get 参数
  getParamsUrl(url, params) {
    if (Object.keys(params).length !== 0) {
      let str = '';
      for (const key in params) {
        str = str !== '' ? `${str}&${key}=${params[key]}` : `${key}=${params[key]}`;
      }
      return `${url}?${str}`;
    } else {
      return url;
    }
  }

  // form data post body
  parseParams(params) {
    let newParams = '';
    const keys = Object.keys(params);
    if (keys.length === 0) {
      return '';
    }
    keys.forEach((key, index) => {
      newParams =
        index === 0
          ? `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
          : `${newParams}&${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`;
    });
    return newParams;
  }
}
